# coding:utf-8

import wx, urllib2, thread, webbrowser, json, time
from distutils.version import StrictVersion
import Global


def AutoCheckVersion():
    try:
        url = Global.app['version_check']
        url = Global.app['download_url']
        if Global.app['version_check'] and Global.app['download_url']:
            thread.start_new_thread(ThreadCheckVersion, ())
    except:
        pass


def ThreadCheckVersion():
    try:
        time.sleep(4)
        response = urllib2.urlopen(Global.app['version_check'])
        json_data = ''
        while True:
            line = response.readline()
            json_data += line.decode('utf-8', 'ignore')
            if not line:
                break
        data = json.loads(json_data)
        version = data['version']

        if StrictVersion(version) > StrictVersion(Global.app['version']):
            dlg = wx.MessageDialog(Global.var['Frame'], u'发现新版本 V' + version + u'，转到下载页？',
                                   style=wx.YES_NO | wx.ICON_QUESTION)
            if wx.ID_YES == dlg.ShowModal():
                webbrowser.open_new_tab(Global.app['download_url'])
    except:
        pass
